package tianqi.controller.WebSocket;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import net.sf.json.JSONObject;

@ServerEndpoint("/ws")
public class ChatServer {

	private Session session;
	private String name;
	private String txImg;
	private ChatServer obj;

	private static List<String> servicePool = new ArrayList<String>(Arrays.asList("service1", "service2"));
	private static Map<String, ChatServer> map = new HashMap<String, ChatServer>();
	private static Map<String, ChatServer> service = new HashMap<String, ChatServer>();

	@OnOpen
	public void start(Session session) throws IOException {

		this.session = session;
		System.out.println(session.getQueryString());
		String[] split = session.getQueryString().split("=");
		if (split.length >= 2) {
			this.name = URLDecoder.decode(split[0], "utf-8");
			this.txImg = split[1];

			if (contains(servicePool, name)) {
				service.put(name, this);
				publicSend("s");
			} else {
				map.put(name, this);
				publicSend("u");
			}

		}
	}

	public void publicSend(String flag) {

		if ("u".equals(flag)) {
			String msg = "";
			String selectService = selectService();

			ChatServer chatServer = service.get(selectService);
			if (chatServer != null) {

				this.obj = chatServer;
				chatServer.obj = this;
				service.remove(selectService);
				for (ChatServer c1 : map.values()) {

					if (c1 == this) {
						// 创建java里面的json对象
						JSONObject jo = new JSONObject();
						jo.accumulate("msg",
								selectService != "" ? "欢迎 登录聊天室     由客服: " + selectService + " 为您服务" : "人工座席繁忙，请您稍后重试");
						jo.accumulate("txImg", "");
						jo.accumulate("name", this.name);
						msg = jo.toString();
						System.out.println(msg);
						this.send(msg);
						// 创建java里面的json对象
						JSONObject jo1 = new JSONObject();
						jo1.accumulate("msg", "已登录   请接单！！！");
						jo1.accumulate("txImg", "");
						jo1.accumulate("name", this.name);
						msg = jo1.toString();
						chatServer.send(msg);
					}
				}

				/*
				 * else { jo.accumulate("msg", " 已 登录聊天室");
				 * jo.accumulate("txImg", ""); jo.accumulate("name", this.name);
				 * msg = jo.toString(); System.out.println(msg); c.send(msg); }
				 */
			} else {
				// 创建java里面的json对象
				JSONObject jo = new JSONObject();
				jo.accumulate("msg", "人工座席繁忙，请您稍后重试");
				jo.accumulate("txImg", "");
				jo.accumulate("name", this.name);
				msg = jo.toString();
				System.out.println(msg);
				this.send(msg);
				try {
					session.close();
				} catch (IOException e) {
					System.out.println("关闭连接失败  at107");
				}
			}
		} else if ("s".equals(flag)) {
			String msg = "";

			this.obj = null;
			// 创建java里面的json对象
			JSONObject jo = new JSONObject();

			jo.accumulate("msg", "您已成功登录  请准备接单！");
			jo.accumulate("txImg", "");
			jo.accumulate("name", this.name);
			msg = jo.toString();
			System.out.println(msg);
			this.send(msg);

			/*
			 * else { jo.accumulate("msg", " 已 登录聊天室"); jo.accumulate("txImg",
			 * ""); jo.accumulate("name", this.name); msg = jo.toString();
			 * System.out.println(msg); c.send(msg); }
			 */
		}
	}

	/**
	 * 抽选一名客服人员
	 */
	public String selectService() {
		String key = "";
		if (service.size() > 0) {
			for (String string : service.keySet()) {
				key = string;
				break;
			}
			return key;
		} else {
			return key;
		}

	}

	public boolean send(String msg) {
		try {
			session.getBasicRemote().sendText(msg);
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	@OnMessage
	public void onmsg(String msg) {
		middleMsg(msg);
	}

	@OnClose
	public void onclose() {
		String msg = "";
		// 创建java里面的json对象
		JSONObject jo = new JSONObject();
		jo.accumulate("msg", "已下线！");
		jo.accumulate("txImg", "");
		jo.accumulate("name", this.name);
		msg = jo.toString();
		System.out.println(msg);
		
		try {
			this.obj.send(msg);
			service.put(this.obj.name, this.obj);
			session.close();
		} catch (IOException e) {
			System.out.println("关闭连接失败  at176");
		}catch (Exception e) {
			System.out.println("this.obj  at178");
		}
	}

	public void middleMsg(String msg) {

		// 创建java里面的json对象
		JSONObject jo = new JSONObject();
		// 在json对象中放入键值对
		jo.accumulate("msg", msg);
		jo.accumulate("txImg", this.txImg == null || this.txImg == "" ? "1" : this.txImg);
		jo.accumulate("name", this.name);
		msg = jo.toString();

		System.out.println(msg);
		this.obj.send(msg);

		/*
		 * for (ChatServer c : map.values()) { if (c != this) { //
		 * 创建java里面的json对象 JSONObject jo = new JSONObject(); // 在json对象中放入键值对
		 * jo.accumulate("msg", msg); jo.accumulate("txImg", this.txImg == null
		 * || this.txImg == "" ? "1" : this.txImg); jo.accumulate("name",
		 * this.name); msg = jo.toString();
		 * 
		 * System.out.println(msg); c.send(msg); } }
		 */
	}

	public void middle(String msg) {
		for (ChatServer c : map.values()) {
			if (c != this) {
				// 创建java里面的json对象
				JSONObject jo = new JSONObject();
				// 在json对象中放入键值对
				jo.accumulate("msg", msg);
				jo.accumulate("txImg", this.txImg == null || this.txImg == "" ? "1" : this.txImg);
				jo.accumulate("name", this.name);
				msg = jo.toString();

				System.out.println(msg);
				c.send(msg);
			}
		}
	}

	public static boolean contains(List<String> list, String s) {
		if (list.size() > 0) {
			for (String string : list) {
				if (s.equals(string)) {
					return true;
				} else {
					return false;
				}
			}
			return false;
		} else {
			return false;
		}

	}
}
